package com.hdoit.ares.web.wechat.handler;

import java.util.Map;

import javax.annotation.Resource;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.hdoit.ares.logical.acc.model.AccountInfo;
import com.hdoit.ares.logical.acc.model.GoldenBeanDetail;
import com.hdoit.ares.logical.acc.service.IAccountInfoService;
import com.hdoit.ares.logical.acc.service.IGoldenBeanDetailService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.selfcommon.enums.acc.GoldenBeanType;
import com.hdoit.ares.selfcommon.enums.acc.HesitatePeriodState;
import com.hdoit.ares.selfcommon.enums.acc.State;
import com.hdoit.ares.selfcommon.enums.cust.AttentionStatus;
import com.hdoit.ares.selfcommon.enums.cust.CustomerLevel;
import com.hdoit.ares.web.wechat.WechatTemplateManager;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.RandomUtils;
import com.tennetcn.web.cbase.wechat.handler.BaseSubscribeHandler;

/**
 * 
 * @author Binary Wang
 *
 */
@Component
public class SubscribeHandler extends BaseSubscribeHandler {

	private ICustomerService customerService;
	private IAccountInfoService accountInfoService;
	private IGoldenBeanDetailService goldenBeanDetailService;
	
	public IGoldenBeanDetailService getGoldenBeanDetailService() {
		return goldenBeanDetailService;
	}

	@Resource
	public void setGoldenBeanDetailService(
			IGoldenBeanDetailService goldenBeanDetailService) {
		this.goldenBeanDetailService = goldenBeanDetailService;
	}

	public IAccountInfoService getAccountInfoService() {
		return accountInfoService;
	}

	@Resource
	public void setAccountInfoService(IAccountInfoService accountInfoService) {
		this.accountInfoService = accountInfoService;
	}

	public ICustomerService getCustomerService() {
		return customerService;
	}

	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	@Override
	protected WxMpXmlOutMessage beforeHandle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
		if (WxConsts.XML_MSG_EVENT.equals(wxMessage.getMsgType())) {
			if (WxConsts.EVT_SUBSCRIBE.equals(wxMessage.getEvent())) {
				String qrsceneId = wxMessage.getEventKey().replace("qrscene_", "");
				String openId = wxMessage.getFromUser();
				// 如果已经关注过，再次关注的
				Customer customer = customerService.queryModelByOpenId(openId);

				/*int refereeIdentity = -1;*/
				//默认没有上级用0标识
				int refereeIdentity = 0;
				if (!StringUtils.isEmpty(qrsceneId)) {
					refereeIdentity = CommonUtils.getNumber(qrsceneId);
				}

				if (customer == null) {
					try {
						WxMpUser mpUser = wxMpService.getUserService().userInfo(openId);
						customer = customerService.addCustomer(openId, mpUser, refereeIdentity);
						
						sendNewVipJoinMessage(customer);
						subscribeNotice(customer, wxMpService, openId);
					} catch (Exception ex) {
					}
				} else {
					/**
					 * 再次关注进来，如果是游客，那么重新设置下引入人 如果没有扫描二维码进来，通过搜索进来，就直接清空上下级关系
					 */
					if (CustomerLevel.visitor.equals(customer.getLevel())) {
						// 先清空
						customer.setRefereeIdentity(0);
						customer.setRefereeId(null);
						// 在取出来设置  //有可能自己关注自己的情况
						if (refereeIdentity > 0&&refereeIdentity!=customer.getUserIdentity()) {
							String customerId = customerService.queryIdByUserIdentity(refereeIdentity);
							if (!StringUtils.isEmpty(customerId)) {
								customer.setRefereeIdentity(refereeIdentity);
								customer.setRefereeId(customerId);
							}
						}
					}

					customer.setAttentionDate(DateUtils.getCurrent());
					customer.setAttentionStatus(AttentionStatus.attention);
					customerService.updateModel(customer);

					// 给其他人发送关注消息  再次进来的不再发送关注通知
					//sendNewVipJoinMessage(customer);

					// 订阅通知消息
					subscribeNotice(customer, wxMpService, openId);
				}
			}
		}
		return null;
	}

	@Override
	protected WxMpXmlOutMessage afterHandle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
		String openId = wxMessage.getFromUser();
		WxMpKefuMessage.WxArticle article1 = new WxMpKefuMessage.WxArticle();
		article1.setUrl("http://mp.weixin.qq.com/s/VE3QVa2rRqTEljbQU24k3w");
		article1.setPicUrl("http://www.putiyoli.net/ares/images/we/message/putiyoli_insurance_easy.jpg");
		article1.setDescription("普天永利，让创业更简单！");
		article1.setTitle("1分钟了解普天永利");
		WxMpKefuMessage.WxArticle article2 = new WxMpKefuMessage.WxArticle();
		article2.setUrl("http://mp.weixin.qq.com/s/7R3krxvyFcPX3XXhbPmdeg");
		article2.setPicUrl("http://www.putiyoli.net/ares/images/we/message/maker.jpg");
		article2.setDescription("你知道创客奖励有什么吗？");
		article2.setTitle("一张图看懂创客奖励");
		WxMpKefuMessage.WxArticle article3 = new WxMpKefuMessage.WxArticle();
		article3.setUrl("http://mp.weixin.qq.com/s/L8jHgjPs2jV6WvqouEu6mA");
		article3.setPicUrl("http://www.putiyoli.net/ares/images/we/message/maker.jpg");
		article3.setDescription("一起加入创客吧");
		article3.setTitle("加入创客流程");
		
		WxMpKefuMessage message =  WxMpKefuMessage.NEWS()
	    .toUser(openId)
	    .addArticle(article1)
	    .addArticle(article2)
	    .addArticle(article3)
	    .build();
		
		/*WxMpKefuMessage picture = WxMpKefuMessage.IMAGE().mediaId("KWpKzT1inSIyPapD8i52AfG42rmo0FQbwecJPwPRjas").toUser(openId).build();
		
		//普天共享商城测试
		//WxMpKefuMessage picture = WxMpKefuMessage.IMAGE().mediaId("j8B2YjYGatZHyD-qcTS7TvNeM2B74luo5mwpodliS7Q").toUser(openId).build();
*/		
		try {
			wxMpService.getKefuService().sendKefuMessage(message);
			/*wxMpService.getKefuService().sendKefuMessage(picture);*/
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		return null;
	}

	private void subscribeNotice(Customer customer, WxMpService wxMpService, String userId) {
		WechatTemplateManager.sendAttentionSuccess(userId, customer);
	}

	// 向上级回复新会员加入通知
	public void sendNewVipJoinMessage(Customer customer) {
		if (customer == null || StringUtils.isEmpty(customer.getRefereeId())) {
			return;
		}
		Customer refereeCustomer = customerService.queryModel(customer.getRefereeId());
		if(refereeCustomer==null||!AttentionStatus.attention.equals(refereeCustomer.getAttentionStatus())){return;}
		
		// 上级是初创或高创，都给通知
		if (CustomerLevel.maker.equals(refereeCustomer.getLevel()) || CustomerLevel.highMaker.equals(refereeCustomer.getLevel())) {
			if(refereeCustomer.getUserIdentity()>1000){
				AccountInfo custAccountInfo = accountInfoService.queryModelByCustomerId(refereeCustomer.getId());
				double goldenBean  = custAccountInfo.getGoldenBean();
				goldenBean += 5;
				custAccountInfo.setGoldenBean(goldenBean);
				custAccountInfo.setModelStatus(ModelStatus.update);
				
				if(accountInfoService.applyChange(custAccountInfo)){
					GoldenBeanDetail goldenBeanDetail = new GoldenBeanDetail();
					goldenBeanDetail.setId(CommonUtils.getKeyId());
					goldenBeanDetail.setAccountNo(custAccountInfo.getAccountNo());
					goldenBeanDetail.setGoldenBeanType(GoldenBeanType.invitation);
					goldenBeanDetail.setTime(DateUtils.getCurrent());
					goldenBeanDetail.setState(State.income);
					goldenBeanDetail.setGoldenBeanAccount(5);
					goldenBeanDetail.setCustomerId(refereeCustomer.getId());
					goldenBeanDetail.setGoldenBeanBalance(goldenBean);
					goldenBeanDetail.setHesitatePeriod(0);
					goldenBeanDetail.setOutTradeNo("" + System.currentTimeMillis()+RandomUtils.randomInt(1000, 9999));
					goldenBeanDetail.setComment("邀请新人奖励");
					goldenBeanDetail.setHesitatePeriodState(HesitatePeriodState.Hesitated);
					
					goldenBeanDetail.setModelStatus(ModelStatus.add);
					goldenBeanDetailService.applyChange(goldenBeanDetail);
				}
			}
			
			WechatTemplateManager.sendUpdateLevel(refereeCustomer.getOpenId(), customer, CustomerLevel.visitor,null,null);
		}
		
		if(StringUtils.isEmpty(refereeCustomer.getRefereeId())){return;}
		
		// 判断上级的上级是创客就给通知
		Customer refereeTwoCustomer = customerService.queryModel(refereeCustomer.getRefereeId());
		if(refereeTwoCustomer==null||!AttentionStatus.attention.equals(refereeTwoCustomer.getAttentionStatus())){return;}
		
		if (CustomerLevel.maker.equals(refereeTwoCustomer.getLevel())||CustomerLevel.highMaker.equals(refereeTwoCustomer.getLevel())) {
			WechatTemplateManager.sendUpdateLevel(refereeTwoCustomer.getOpenId(), customer, CustomerLevel.visitor,refereeCustomer,null);
		}
	}
}
